import CryptoJS from 'crypto-js'
import JSEncrypt from 'jsencrypt'

const parse = CryptoJS.enc.Latin1.parse

export function hash(input) {
  return CryptoJS.SHA256(input).toString()
}

export class RSAAESDecrypter {
  encrypter = null
  publickey = null
  constructor(publickey) {
    this.encrypter = new JSEncrypt()
    this.encrypter.setPublicKey(publickey)
  }

  randString(length = 16) {
    let str = ''
    while (str.length < length) {
      str += Math.random().toString(36).substr(2)
    }
    return str.substr(0, length)
  }

  buildAesConfig(iv) {
    return {
      iv: parse(iv),
      mode: CryptoJS.mode.CBC
    }
  }

  aesEncrypt(origin, key, iv) {
    const config = this.buildAesConfig(iv)
    const encrypted = CryptoJS.AES.encrypt(origin, parse(key), config)
    return encrypted.toString()
  }

  aesDecrypt(encrypted, key, iv) {
    const config = this.buildAesConfig(iv)
    const decrypted = CryptoJS.AES.decrypt(encrypted, parse(key), config)
    return decrypted.toString(CryptoJS.enc.Utf8)
  }

  rsaEncrypt(input) {
    return this.encrypter.encrypt(input)
  }

  /**
   * 将原密码加密为加密后的密码、enkey和iv
   * @param {string} password 原密码
   */
  encryptPassword(password) {
    const key = this.randString(16)
    const iv = this.randString(16)
    const enkey = this.rsaEncrypt(key)
    const enpassword = this.aesEncrypt(password, key, iv)
    return {
      password: enpassword,
      enkey,
      iv
    }
  }
}
